// 一套完整的CRUD实现
import users from '../models/user'
import { apiFailed, parseJson, response } from '../utils'
const Mock = require('mockjs')

export default [
  {
    user: '/api/user',
    method: 'get',
    response: users
  },
  {
    url: '/api/user/:id',
    method: 'get',
    response: ({query}) => {
      return users.find(item => item.id.toString() === query.id)
    }
  },
  {
    url: '/api/user',
    method: 'post',
    rawResponse: async(req, res) => {
      const instance = await parseJson(req)
      if(users.find(item => item.username === instance.username)){
        return apiFailed(res, '用户名重复')
      }
      instance.id = Mock.mock('@increment')
      users.push(instance)
      return response(res, instance)
    }
  },
  {
    url: '/api/user/:id',
    method: 'put',
    response: ({query, body}) => {
      const instance = users.find(item => item.id.toString() === query.id)
      instance && Object.assign(instance, body)
      return instance
    }
  },
  {
    url: '/api/user/:id',
    method: 'delete',
    response: ({query}) => {
      const instance = users.find(item => item.id.toString() === query.id)
      instance && users.splice(users.indexOf(instance))
      return {}
    }
  }
]